package com.list88zhu.android.sunflower.http;

import android.support.v4.util.ArrayMap;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import retrofit2.Retrofit;

/**
 * <pre><code>
 *
 *  </code></pre>
 *
 * @author zhuyingming@qmtv.com
 * @date 2018/9/9
 */
public class Api {

    private static Lock lock = new ReentrantLock();
    protected static ConfigParam configParams;
    private static ArrayMap<String, ApiProxy> apiProxies = new ArrayMap<>();


    public static void init(ConfigParam params) {
        configParams = params;
    }

    public static ApiProxy create(Class<? extends Config> cls) {
        if (cls == null) {
            throw new IllegalArgumentException("config can't be null.");
        }
        String clsName = cls.getCanonicalName();
        ApiProxy apiProxy = apiProxies.get(clsName);
        if (apiProxy == null) {
            lock.lock();
            apiProxy = new ApiProxy(newRetrofit(cls));
            apiProxies.put(clsName, apiProxy);
            lock.unlock();
        }
        return apiProxy;
    }

    private static Retrofit newRetrofit(Class<? extends Config> config) {
        Retrofit.Builder builder = new Retrofit.Builder();
        try {
            config.newInstance().build(builder, configParams);
        }catch (InstantiationException e) {
            e.printStackTrace();
        }catch (IllegalAccessException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return builder.build();
    }




    /**
     * 参数配置
     */
    public static class ConfigParam{
        public boolean isDebug;
        public boolean isOnline;
        public String versionName;
        public String channel;

        @Override
        public String toString() {
            return "ConfigParam: {" +
                "isDebug:"+isDebug+"," +
                "isOnline:"+isOnline+"," +
                "versionName:'"+versionName+"',"+
                "channel:"+channel+
                "}";
        }
    }

    public interface Config{
        /**
         * 创建具体的retrofit
         *
         * Retrofit retrofit = new Retrofit.Builder()
         * client(clientBuilder.build())
         * baseUrl("https://news-at.zhihu.com")
         * addConverterFactory(GsonConverterFactory.create())
         * build();
         *
         * @param builder
         * @param configParams
         */
        void build(Retrofit.Builder builder, ConfigParam configParams);
    }
}
